import { ref, reactive } from 'vue';
import { ElMessage, dayjs } from 'element-plus';
import demandApi from '@/apis/demand';

/**
 * 需求大厅相关的Hook
 */
export function useDemandHall() {
  // 状态管理
  const loading = ref(false);
  const demands = ref([]);
  const currentDemand = ref(null);
  const detailDialogVisible = ref(false);
  
  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });
  
  // 搜索条件
  const searchParams = reactive({
    keyword: '',
    minBudget: null,
    maxBudget: null
  });
  
  /**
   * 获取需求大厅列表数据
   * 只显示已发布(3)和已接单(4)状态的需求
   */
  const fetchDemandList = async () => {
    loading.value = true;
    
    try {
      const params = {
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        title: searchParams.keyword,
        // 筛选已发布和已接单状态的需求
        status: [3, 4]
      };
      
      // 只在有值时添加预算范围参数
      if (searchParams.minBudget !== null && searchParams.minBudget !== '') {
        params.minBudget = searchParams.minBudget;
      }
      if (searchParams.maxBudget !== null && searchParams.maxBudget !== '') {
        params.maxBudget = searchParams.maxBudget;
      }
      
      // 调用真实API
      const response = await demandApi.getDemandList(params);
      
      if (response.code === 200 && response.data) {
        // 格式化数据，使用小驼峰命名
        demands.value = response.data.records.map(item => ({
          id: item.id,
          userId: item.userId,
          userType: item.userType,
          title: item.title,
          description: item.description,
          budget: item.budget,
          deadline: dayjs(item.deadline).format('YYYY-MM-DD'),
          status: item.status,
          publishTime: dayjs(item.publishTime).format('YYYY-MM-DD HH:mm:ss'),
          createTime: dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss'),
          acceptedEnterprise: item.acceptedEnterprise ? {
            id: item.acceptedEnterprise.id,
            name: item.acceptedEnterprise.name,
            description: item.acceptedEnterprise.description
          } : null
        }));
        
        pagination.total = response.data.total;
      }
    } catch (error) {
      console.error('获取需求列表失败:', error);
      ElMessage.error('获取需求列表失败');
    } finally {
      loading.value = false;
    }
  };
  
  /**
   * 查看需求详情
   * @param {Object} demand 需求对象
   */
  const viewDemandDetail = async (demand) => {
    loading.value = true;
    try {
      // 调用需求详情API获取完整信息
      const response = await demandApi.getDemandDetail(demand.id);
      
      if (response.code === 200 && response.data) {
        // 格式化数据，保持与前端期望的结构一致
        currentDemand.value = {
          id: response.data.id,
          userId: response.data.userId,
          userType: response.data.userType,
          title: response.data.title,
          description: response.data.description,
          budget: response.data.budget,
          deadline: dayjs(response.data.deadline).format('YYYY-MM-DD'),
          status: response.data.status,
          publishTime: dayjs(response.data.publishTime).format('YYYY-MM-DD HH:mm:ss'),
          createTime: dayjs(response.data.createTime).format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs(response.data.updateTime).format('YYYY-MM-DD HH:mm:ss'),
          acceptedEnterprise: response.data.acceptedEnterprise ? {
            id: response.data.acceptedEnterprise.id,
            name: response.data.acceptedEnterprise.name,
            description: response.data.acceptedEnterprise.description
          } : null
        };
        detailDialogVisible.value = true;
      }
    } catch (error) {
      console.error('获取需求详情失败:', error);
      ElMessage.error('获取需求详情失败');
    } finally {
      loading.value = false;
    }
  };
  
  /**
   * 关闭详情对话框
   */
  const closeDetailDialog = () => {
    detailDialogVisible.value = false;
    currentDemand.value = null;
  };
  
  /**
   * 企业接单
   * @param {Number} demandId 需求ID
   */
  const acceptDemand = async (demandId) => {
    try {
      // 模拟企业ID，实际应用中应该从用户状态获取
      const enterpriseId = 1; // 这里需要替换为实际的企业ID
      
      // 调用真实API
      const response = await demandApi.selectEnterprise(demandId, enterpriseId);
      
      if (response.code === 200 && response.data) {
        ElMessage.success('接单成功');
        closeDetailDialog();
        fetchDemandList(); // 重新加载需求列表
      } else {
        ElMessage.error('接单失败');
      }
    } catch (error) {
      console.error('接单失败:', error);
      ElMessage.error('接单失败');
    }
  };
  
  /**
   * 搜索需求
   */
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchDemandList();
  };
  
  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    searchParams.keyword = '';
    searchParams.minBudget = null;
    searchParams.maxBudget = null;
    pagination.currentPage = 1;
    fetchDemandList();
  };
  
  /**
   * 分页大小变化
   */
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchDemandList();
  };
  
  /**
   * 页码变化
   */
  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    fetchDemandList();
  };
  
  /**
   * 获取需求状态文本
   */
  const getStatusText = (status) => {
    const statusMap = {
      3: '已发布',
      4: '已接单',
      5: '进行中',
      6: '已完成',
      7: '已关闭'
    };
    return statusMap[status] || '未知状态';
  };
  
  /**
   * 获取需求状态标签类型
   */
  const getStatusTagType = (status) => {
    const typeMap = {
      3: 'primary',
      4: 'success',
      5: 'warning',
      6: 'info',
      7: 'danger'
    };
    return typeMap[status] || 'info';
  };
  
  /**
   * 格式化预算
   */
  const formatBudget = (budget) => {
    if (budget === null || budget === undefined) {
      return '面议';
    }
    return `¥${budget.toFixed(2)}`;
  };
  
  /**
   * 截断文本
   */
  const truncateText = (text, maxLength) => {
    if (!text || text.length <= maxLength) {
      return text;
    }
    return text.substring(0, maxLength) + '...';
  };
  
  return {
    // 状态
    loading,
    demands,
    currentDemand,
    detailDialogVisible,
    pagination,
    searchParams,
    
    // 方法
    fetchDemandList,
    viewDemandDetail,
    closeDetailDialog,
    acceptDemand,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    getStatusText,
    getStatusTagType,
    formatBudget,
    truncateText
  };
}